package com.hk.utils;

import com.hk.exception.BizException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Objects;

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 手动在Spring容器中获取一个对象
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 通过名称获取bean
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 根据service接口获取对应的实体类
     *
     * @param service
     * @return
     */
    public static Class getEntity(Class service) {
        Type[] types = service.getGenericInterfaces();

        if (Objects.isNull(types)) {
//            throw BizException.
//                    convertActiveErrorMessage(ErrorEnum.ACTIVE_PARAM_INPUT_VALID, "查询列表功能反射获取实体类",
//                            "service", "无法通过该入参获取正确的实体类");
            throw new BizException("无法通过该入参获取正确的实体类");
        }

        Type genericSuperclass = types[0];
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;

        // 获取超类的泛型类型数组. 即SuperClass<User>的<>中的内容, 因为泛型可以有多个, 所以用数组表示
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        Type genericType = actualTypeArguments[0];
        return (Class) genericType;

    }

}
